#include "stm32g030xx.h"
#include <stdint.h>
#include "Motor_Ext.h"
#include "adc.h"

#define M2M_CHANNEL (DMA1_Channel5)
extern uint16_t g_AdcDmaCacheBuffer[];
extern void adcDMAFinishCallBack(void);
void DMA_Init(void)
{
   RCC->AHBENR |= 0x01; //使能DMA时钟

   DMA1_Channel1->CCR &=~ 0X01; //失能DMA
   DMA1_Channel1->CCR = 0X000035A2;//priority level:very high  MSIZE:16 bits  PSIZE:16 bits  
                                   //MINC:incremental mode  CIRC:enabled  DIR:peripheral to memory
                                   //TCIE:enabled
   DMA1_Channel1->CPAR = (uint32_t)(&ADC1->DR); //DMA传输地址，ADC数据寄存器
   DMA1_Channel1->CMAR = (uint32_t)(&g_AdcDmaCacheBuffer[0]); //DMA接收地址，ADC数据缓冲区
   DMA1_Channel1->CNDTR = 5; //传输次数

   DMAMUX1_Channel0->CCR = 5;//DMA多路选择器输入5(ADC),发送至DMA CH1
   DMA1_Channel1->CCR |= 0X01; //使能DMA

   /*配置M2M专用通道*/
   M2M_CHANNEL -> CCR &=~ 0X01; //失能DMA
   M2M_CHANNEL -> CCR = 0X000050C2;
}

void DMA_Enable(void)
{
    // 启用DMA1的通道1
    DMA1_Channel1->CCR |= 0X01;
}

void DMA_M2M_Transfer(void const * const src,void const * const dst,uint16_t len)
{
    M2M_CHANNEL->CPAR = (uint32_t)src;
    M2M_CHANNEL->CMAR = (uint32_t)dst;
    M2M_CHANNEL->CNDTR = len;
    M2M_CHANNEL->CCR |= 0X01; //使能DMA
}

void DMA1_Channel1_IRQHandler(void)
{
    adcDMAFinishCallBack();
    eMotorStateMachine();
    
    DMA1->IFCR = 0xFFFFFFFF;
}
